<?php
namespace app\api\controller;
use think\Config;
use think\Request;
use think\Db;
use app\api\model\Show;
class Payment extends Base
{

    //测试服务器
    private     $domain = "https://www.taoyiapp.com";
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    //下单
    public function order(){

        $order_sn = $this->generateOrderNo();

        $data['order_sn'] = $order_sn;

        $data['uid'] = input('uid');

        $data['goods_id'] = input('goods_id');

        $data['goods_name'] =input('goods_name');

        $data['price'] = input('price');

        if($data['price']<0.01){
            $this->ajaxReturn('',-1, '金额必须大于0.01元');
        }

        $data['status'] = 0;

        $data['level'] = input('level');

        $data['created_at'] = time();

        $order_id = db('order')->insertGetId($data);

        if($order_id){
            //获取订单号
            $where['order_sn'] = $data['order_sn'];
            //查询订单信息
            $order_info = db('order')->where($where)->find();
            $reoderSn = $order_info['order_sn'];
    
            //获取支付金额
            $money = $data['price'];//$order_info['realprice'];
            //判断支付方式
/*
                $type['paytype'] = 1;

                db('order')->where($where)->update($type);*/

                $alipay = new Alipay();

                //异步回调地址
                $url = $this->url_translation_address('/api/Payment/alipay_notify');

                $array = $alipay ->alipay(Config::get('alipay')['company'], $money, $reoderSn, $url);

                if ($array) {
                    
                return json(['data'=>$array]);
                   /* return $this->ajaxReturn($array, 1, '成功');*/
                } else {

                    return $this->ajaxReturn('', 0, '对不起请检查相关参数');
                }
            
        }

    }

    public function payOrder()
    {
/*        if ($pay_type == 'wechat') {
            $type['paytype'] = 2;
        }*/

    }

    /*
         * 支付宝支付回调修改订单状态
         */
    public function alipay_notify()
    {

        import('.Alipay.aop.AopClient','', '.php');
        import('.Alipay.aop.request.AlipayTradeAppPayRequest', '', '.php');

        //验签
        $aop = new \AopClient();
        $aop->alipayrsaPublicKey = Config::get('alipay')['alipayrsaPublicKey'];
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");
        if(!$flag){
            return false;
        }

        //原始订单号
        $out_trade_no = input('out_trade_no');
        //支付宝交易号
        $trade_no = input('trade_no');
        //交易状态
        $trade_status = input('trade_status');

        $order = db('order')->where('order_sn',$out_trade_no)->find();
      
        if(!$order){
            return false;
        }

        $task_num = db('member')->where('level',$order['level'])->value('task_num');
        file_put_contents('level.txt',$order['level']);
        file_put_contents('task_num.txt',$task_num);

        if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {

            $condition['order_sn'] = $out_trade_no;
            $data['status'] = 1;
            $data['third_ordersn'] = $trade_no;


            //修改订单状态,支付宝单号到数据库

            // 启动事务
/*        Db::startTrans();
        try{*/

            $result=db('order')->where($condition)->update($data);
            file_put_contents('test.txt',$result);

            //更改会员信息
            $level['level'] = $order['level'];
            $level['day_num'] = $task_num;
            $date = date("Y-m-d");
            $level['day_time'] = strtotime($date);
            
            db('user_account')->where('id',$order['uid'])->update($level);

            //查询推荐人 一级
            $recommend_one = db('team')->where('uid',$order['uid'])->value('recommend_id');
     

            //查询推荐人 二级
            if(!empty($recommend_one)){
                $recommend_two = db('team')->where('uid',$recommend_one)->value('recommend_id');
                file_put_contents('recommend_two.txt',$recommend_two);
            }
            

            //更新会员详情
            $member['uid'] = $order['uid'];
            $member['level'] = $order['level'];
            $member['price'] = $order['price'];

            $member['recommend_id'] = $recommend_one;
            $member['created_at'] = time();
            /*var_dump($member);die;*/
            db('member_info')->insert($member);

            if(!empty($recommend_one)){

                $level = db('user_account')->where('id',$recommend_one)->value('level');

                if($level==1){

                    $tc_type =3;

                }elseif($level==2){

                    $tc_type =9;   
                }

                $one_task = db('proportion')->where('tc_type',$tc_type)->value('tc_price');

               /* $one_task = db('proportion')->where('tc_type',3)->value('tc_price');*/
                /*var_dump($one_task);die;*/
                //通过要插入佣金表
                $commission['uid'] = $recommend_one;
                /*$commission['recommend_id'] = $recommend_id;*/
                $commission['commission'] = ($order['price']*$one_task/100);
                /*var_dump($commission);die;*/
                $commission['type'] = 2;
                $commission['created_at'] = time();
                db('team2_commission')->insert($commission);
            }

            if(!empty($recommend_two)){

                $level = db('user_account')->where('id',$recommend_two)->value('level');

                if($level==1){

                    $tc_type = 5;

                }elseif($level==2){

                    $tc_type = 11;   
                }

                $two_task = db('proportion')->where('tc_type',$tc_type)->value('tc_price');
                file_put_contents('22222222222222222.txt',$recommend_two);
             /*   $two_task = db('proportion')->where('tc_type',5)->value('tc_price');*/
                //通过要插入佣金表
                $commission['uid'] = $recommend_two;
                /*$commission['recommend_id'] = $recommend_id;*/
                $commission['commission'] = ($order['price']*$two_task/100);
                $commission['type'] = 2;
                $commission['created_at'] = time();
                db('team1_commission')->insert($commission);
            }

            //查询是否有代理
            $user = db('user_account')->where('id',$order['uid'])->find();
            $region = db('region')->where('province',$user['province'])->where('city',$user['city'])->where('county',$user['county'])->find();
            if($region){

                $level = db('user_account')->where('id',$region['uid'])->value('level');

                if($level==1){

                    $tc_type = 6;

                }elseif($level==2){

                    $tc_type = 7;   
                }

                $bili = db('proportion')->where('tc_type',$tc_type)->value('tc_price');
                $re_com['uid'] = $region['uid'];
                $re_com['commission'] = $order['price']*$bili/100;
                $re_com['type'] = 2;
                $re_com['created_at'] = time();
                db('region_commission')->insert($re_com);
            }
            
            //更改团队表
            $team['uid'] = $order['uid'];

            $team['level'] = $order['level']; 

            db('team')->where('uid',$order['uid'])->update($team);

            // 提交事务
           /* Db::commit();*/
           echo "success";die;
          /*  return $this->ajaxReturn('',1,'支付成功'); */  
 /*       } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('',-1,'数据更新失败');
        }*/

        }
        return $this->ajaxReturn('',-1,'支付失败');
    }

   //相对地址转绝对地址
    public function url_translation_address($url)
    {
        return $this->domain . $url;
    }

    /**
    * 订单号
    */
    public function generateOrderNo(){
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =$yearCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 999));

        return $orderSn;
    }


}

?>